/////////////////////////////////////////////////////////////////////////////
// 2023 -
//open source under Apache License Version 2.0
/////////////////////////////////////////////////////////////////////////////
//  Modifications by Kumo Inc.
// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//


#include <mutex>
#include <kmhdfs/client/system_ec_policies.h>
#include <turbo/log/logging.h>
#include <turbo/strings/str_format.h>

namespace Hdfs {

namespace Internal {

std::shared_mutex SystemECPolicies::mutex;

SystemECPolicies::SystemECPolicies() {
    std::shared_ptr<ECPolicy> replicationPolicy = std::shared_ptr<ECPolicy>(
        new ECPolicy(REPLICATION, cellsize, 1, 2, "REPLICATION"));
    std::shared_ptr<ECPolicy> sysPolicy1 = std::shared_ptr<ECPolicy>(
        new ECPolicy(RS_6_3, cellsize, 6, 3, "RS"));
    std::shared_ptr<ECPolicy> sysPolicy2 = std::shared_ptr<ECPolicy>(
        new ECPolicy(RS_3_2, cellsize, 3, 2, "RS"));
    std::shared_ptr<ECPolicy> sysPolicy3 = std::shared_ptr<ECPolicy>(
        new ECPolicy(RS_6_3_LEGACY, cellsize, 6, 3, "RS-LEGACY"));
    std::shared_ptr<ECPolicy> sysPolicy4 = std::shared_ptr<ECPolicy>(
        new ECPolicy(XOR_2_1, cellsize, 2, 1, "XOR"));
    std::shared_ptr<ECPolicy> sysPolicy5 = std::shared_ptr<ECPolicy>(
        new ECPolicy(RS_10_4, cellsize, 10, 4, "RS"));
    sysPolicies = {replicationPolicy, sysPolicy1, sysPolicy2, 
                   sysPolicy3, sysPolicy4, sysPolicy5};
    if (maps.empty()) {
        for (int i = 0; i < (int)sysPolicies.size(); ++i) {
            VKLOG(300)<<turbo::str_format( "ecpolicy name=%s\n", sysPolicies[i]->getName());
            maps.insert(std::make_pair(sysPolicies[i]->getId(), sysPolicies[i]));
        }
    }
}

std::shared_ptr<ECPolicy> SystemECPolicies::getById(int8_t id) {
    std::shared_lock<std::shared_mutex> lock(mutex);
    auto it  = maps.find(id);
    return it != maps.end() ? it->second : nullptr;
}

void SystemECPolicies::addEcPolicy(int8_t id, std::shared_ptr<ECPolicy> ecPolicy) {
    std::unique_lock<std::shared_mutex> lock(mutex);
    sysPolicies.push_back(ecPolicy);
    maps.insert(std::make_pair(id, ecPolicy));
}

}
}
